
//
//  XPTabBarController.swift
//  PPKit
//
//  Created by xiaopin on 16/8/31.
//  Copyright © 2016年 pinguo. All rights reserved.
//

import UIKit

class XPTabBarController: ESTabBarController {
    //MARK: 公开属性
    
    //MARK: 私有属性
    var isFirstLoaded = true
    var currentIndex = 0
    
    let v1 = XPInfoHomeViewController()
    let v2 = XPVideoHomeViewController()
    let v3 = XPShopHomeViewController() //pp_storyBoard("My", "MTMeHomeViewController")
    let v4 = XPMeHomeViewController()
    var tabValues = [(id:Int,key:String,name:String,icon0:String,icon1:String)]()
    var tabVCs = [XPBaseViewController]()
    
    //MARK: 懒加载
    //MARK: 指定某个控制器可以横屏旋转
    override var shouldAutorotate: Bool{
        if self.selectedViewController?.isKind(of: UINavigationController.self) ?? false{
//            let navVC = self.selectedViewController as! UINavigationController
//            if navVC.topViewController?.isKind(of: MTMatchDetailViewController.self) ?? false {
//                return true
//            }
        }
        return false
    }
    
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask{
        if self.selectedViewController?.isKind(of: UINavigationController.self) ?? false {
//            let navVC = self.selectedViewController as! UINavigationController
//            if navVC.topViewController?.isKind(of: MTMatchDetailViewController.self) ?? false {
//                return .allButUpsideDown
//            }
        }
        return .portrait
    }
    
    override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation{
        return .portrait
    }
    
    //MARK: 默认基类方法
    override var preferredStatusBarStyle: UIStatusBarStyle{
        return .default
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        initData()
        initNotification()
        loadData()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }
    
    //主题色切换
    override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
        super.traitCollectionDidChange(previousTraitCollection)
        
        if #available(iOS 13.0, *){
            if traitCollection.hasDifferentColorAppearance(comparedTo: previousTraitCollection){
                PPLog("XPTabBarController hasDifferentColorAppearance")
                refreshTabBar()
            }
        }
    }
}

//MARK: #重写基类方法#
extension XPTabBarController{
    /// 初始化数据
    func initData() {
        //umengLogEvent("tabbar_id", label: titleArr[currentIndex])
        
        tabVCs.removeAll()
        tabVCs.append(v1)
        tabVCs.append(v2)
        tabVCs.append(v3)
        tabVCs.append(v4)
        
        tabValues.removeAll()
        tabValues.append((id:1,key:"info",name:"首页",icon0:"tabbar_bifen",icon1:"tabbar_bifen_selected"))
        tabValues.append((id:1,key:"video",name:"视频",icon0:"tabbar_data",icon1:"tabbar_data_selected"))
        tabValues.append((id:1,key:"shop",name:"商城",icon0:"tabbar_shouchang",icon1:"tabbar_shouchang_selected"))
        tabValues.append((id:1,key:"me",name:"我的",icon0:"tabbar_wode",icon1:"tabbar_wode_selected"))
        
        if #available(iOS 15, *) {
            let bar = UITabBarAppearance.init()
            bar.backgroundColor = pp_color(.CFFFFFF)
            bar.shadowImage = UIImage()
//            let selTitleAttr = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 13),
//                                NSAttributedString.Key.foregroundColor: UIColor.red]
//            bar.stackedLayoutAppearance.selected.titleTextAttributes = selTitleAttr
            self.tabBar.scrollEdgeAppearance = bar
            self.tabBar.standardAppearance = bar
        }
    }
    
    /// 初始化通知
    func initNotification(){
        
        NotificationCenter.default.addObserver(forName: .xpfLoginStatusChanged , object: nil, queue: .main) { [weak self ](notify) in
           
        }
        
        
    }
    
    /// 首次加载数据
    func loadData() {
        initMainVC()
    }
}

//MARK: #自定义方法#
extension XPTabBarController{
    func initMainVC() {
        var vcs = [UIViewController]()
        for (i,item) in tabValues.enumerated() {
            tabVCs[i].tabBarItem = ESTabBarItem(SpringBouncesContentView(),title: item.name, image: UIImage(named: item.icon0), selectedImage: UIImage(named: item.icon1))
            tabVCs[i].title = item.name
            let nvc = XPNavigationController(rootViewController: tabVCs[i])
            vcs.append(nvc)
        }
        self.viewControllers = vcs
        //self.tabBar.backgroundColor = pp_color(#colorLiteral(red: 1, green: 1, blue: 1, alpha: 0.1),#colorLiteral(red: 0.1529411765, green: 0.1529411765, blue: 0.1882352941, alpha: 0.7))
        self.delegate = self
    }
    
    func refreshTabBar(){
        //获取主题样式
        var trait = UITraitCollection.init(userInterfaceStyle: .unspecified)
        let mode = XPApplication.shared.themeMode.rawValue
        switch mode {
        case "ME_ThemeMode_Dark":
            trait = UITraitCollection.init(userInterfaceStyle: .dark)
        case "ME_ThemeMode_Light":
            trait = UITraitCollection.init(userInterfaceStyle: .light)
        default:
            trait = UITraitCollection.init(userInterfaceStyle: .unspecified)
        }
        
        for (i,item) in tabValues.enumerated() {
            //根据主题重置
            tabVCs[i].tabBarItem = ESTabBarItem(TopTipsContentView(),title: item.name, image: UIImage(named: item.icon0, in:nil, compatibleWith: trait), selectedImage: UIImage(named: item.icon1, in:nil, compatibleWith: trait))
            //取消提示标签
            ((tabVCs[i].tabBarItem as? ESTabBarItem)?.contentView as? TopTipsContentView)?.tipMsg = nil
        }
    
        //添加提醒的方式
         //常规
        
//         if let tabBarItem = v1.tabBarItem as? ESTabBarItem {
//            tabBarItem.badgeValue = "New"
//            tabBarItem.titlePositionAdjustment = UIOffset(horizontal: 0, vertical: -2)
//         }
//         if let tabBarItem = v2.tabBarItem as? ESTabBarItem {
//            tabBarItem.badgeValue = "99+"
//            tabBarItem.titlePositionAdjustment = UIOffset(horizontal: 0, vertical: -2)
//         }
//         //自定义颜色圆
//         if let tabBarItem = v3.tabBarItem as? ESTabBarItem {
//            tabBarItem.badgeValue = "1"
//            tabBarItem.badgeColor = UIColor.blue
//            tabBarItem.titlePositionAdjustment = UIOffset(horizontal: 0, vertical: -2)
//         }
//         //红点
//         if let tabBarItem = v4.tabBarItem as? ESTabBarItem {
//            tabBarItem.badgeValue = ""
//            tabBarItem.titlePositionAdjustment = UIOffset(horizontal: 0, vertical: -2)
//         }
//         //不显示
//         if let tabBarItem = v5.tabBarItem as? ESTabBarItem {
//            tabBarItem.badgeValue = nil
//            tabBarItem.titlePositionAdjustment = UIOffset(horizontal: 0, vertical: -2)
//         }
        /*
        adModels.forEach { (model) in
            switch model.tabbar_id{
            case 2:
                if model.image?.isNotNullOrEmpty() == true{
                    (v1.tabBarItem as? ESTabBarItem)?.adImgUrl = model.image
                }else{
                    ((v1.tabBarItem as? ESTabBarItem)?.contentView as? TopTipsContentView)?.tipMsg = model.popup_msg
                }
            case 6:
                if model.image?.isNotNullOrEmpty() == true{
                    (v2.tabBarItem as? ESTabBarItem)?.adImgUrl = model.image
                }else{
                    ((v2.tabBarItem as? ESTabBarItem)?.contentView as? TopTipsContentView)?.tipMsg = model.popup_msg
                }
            case 5:
                if model.image?.isNotNullOrEmpty() == true{
                    (v3.tabBarItem as? ESTabBarItem)?.adImgUrl = model.image
                }else{
                    ((v3.tabBarItem as? ESTabBarItem)?.contentView as? TopTipsContentView)?.tipMsg = model.popup_msg
                }
            case 99:
                if model.image?.isNotNullOrEmpty() == true{
                    (v4.tabBarItem as? ESTabBarItem)?.adImgUrl = model.image
                }else{
                    ((v4.tabBarItem as? ESTabBarItem)?.contentView as? TopTipsContentView)?.tipMsg = model.popup_msg
                }
            default:break
            }
        }*/
    }
}

//MARK: #事件通知#
extension XPTabBarController{
    
}

//MARK: #委托代理#
extension XPTabBarController:UITabBarControllerDelegate{
    func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
        currentIndex = tabBarController.selectedIndex
        if isFirstLoaded {return}
        let vc = tabVCs[currentIndex]
        
        (vc.tabBarItem as? ESTabBarItem)?.adImgUrl = nil
        ((vc.tabBarItem as? ESTabBarItem)?.contentView as? TopTipsContentView)?.tipMsg = nil
        
        umengLogEvent("tabbar_id", label: tabValues[currentIndex].name)
    }
}

class SpringBouncesContentView: ESTabBarItemContentView {
    
    public var duration = 0.3
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        //灰色
        textColor = pp_color(.C777777)
        iconColor = pp_color(.C777777)
        //蓝色
        highlightTextColor = pp_color(.C159F48)
        highlightIconColor = pp_color(.C159F48)
        
        renderingMode = .alwaysOriginal
    }
    
    public required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func selectAnimation(animated: Bool, completion: (() -> ())?) {
        self.bounceAnimation()
        completion?()
    }
    
    override func reselectAnimation(animated: Bool, completion: (() -> ())?) {
        self.bounceAnimation()
        completion?()
    }
    
    func bounceAnimation() {
        let impliesAnimation = CAKeyframeAnimation(keyPath: "transform.scale")
        impliesAnimation.values = [1.0 ,1.4, 0.9, 1.15, 0.95, 1.02, 1.0]
        impliesAnimation.duration = duration * 2
        impliesAnimation.calculationMode = CAAnimationCalculationMode.cubic
        imageView.layer.add(impliesAnimation, forKey: nil)
    }
}

class TopTipsContentView: SpringBouncesContentView {
    
    var tipMsg:String? {
        willSet{
            if let str = newValue {
                tipsLabel.text = str
                tipsLabel.isHidden = false
                arrowView.isHidden = false
                layoutIfNeeded()
            }else{
                tipsLabel.isHidden = true
                arrowView.isHidden = true
            }
        }
    }

    var tipsLabel: UILabel = {
        let tipsLabel = UILabel.init(frame: CGRect.zero)
        tipsLabel.textAlignment = .center
        //tipsLabel.text = "提示信息"
        tipsLabel.font = .systemFont(ofSize: 13, weight: .medium)
        tipsLabel.textColor = UIColor.white
        tipsLabel.backgroundColor = pp_color(.C159F48)
        return tipsLabel
    }()
    
    var arrowView: UIImageView = {
        let arrowView = UIImageView.init(image: UIImage.init(named: "arr_down"))
        return arrowView
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.addSubview(self.tipsLabel)
        self.addSubview(self.arrowView)
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        arrowView.frame = CGRect.init(x: 0, y: -8, width: 11, height: 6)
        arrowView.center.x = self.center.x
        
        tipsLabel.frame = CGRect.init(x: 0, y: -43, width: 50, height: 35)
        tipsLabel.cornerRadius = 17.5
        tipsLabel.width = tipsLabel.autoWidth() + 40
        let rect = arrowView.convert(arrowView.frame, to: pp_keyWindow())
        let screenCenterX = rect.origin.x + rect.size.width / 2
        if (screenCenterX + tipsLabel.width / 2) > pp_screen_width {
            //超出屏幕右边宽度
            tipsLabel.center.x = arrowView.center.x - tipsLabel.width / 2 + arrowView.center.x
        }else if (screenCenterX - tipsLabel.width / 2) < 0{
            //超出屏幕左边宽度
            tipsLabel.x = 0
        }else{
            tipsLabel.center.x = arrowView.center.x
        }
    }
    
    public required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
